﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Rung.Net.Cache;
using Rung.Net.Events;
using Rung.Net.Test.Utilities;
using System.Diagnostics;
using Rung.Net.Enums;

namespace Rung.Net.Test
{
    public partial class CacheMainFormC : Form
    {
        CacheClient client = new CacheClient();

        public CacheMainFormC()
        {
            InitializeComponent();
        }

        private void CacheMainFormC_Load(object sender, EventArgs e)
        {
            client.OnConnected += new NetConnectedEventHandler(client_OnConnected);
            client.OnDisconnected += new NetDisconnectedEventHandler(client_OnDisconnected);
            client.OnCacheProcessChanged += new CacheProcessChangedEventHandler(client_OnCacheProcessChanged);
            client.OnReceived += new NetReceivedEventHandler<byte[]>(client_OnReceived);
            client.OnFileTransferComplited += new FileTransferComplitedEventHandler(client_OnFileTransferComplited);

            List<System.Net.IPAddress> ips = NetUtility.GetLocalIpV4();
            string[] configIps = System.Configuration.ConfigurationManager.AppSettings["ips"].Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string ip in configIps)
            {
                ddlAddresses.Items.Add(ip);
            }
            ddlAddresses.DataSource = ips;
        }

        private void CacheMainFormC_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.client.Dispose();
        }

        // 【连接】
        private void btnConnect_Click(object sender, EventArgs e)
        {
            string port = System.Configuration.ConfigurationManager.AppSettings["Cache_ServerPort"];
            client.TryConnect(((System.Net.IPAddress)ddlAddresses.SelectedItem).ToString(), int.Parse(port));
        }

        // 【断开】
        private void btnDisconnect_Click(object sender, EventArgs e)
        {
            client.Disconnect();
        }

        // 【发送字节数组】
        private void btnSendBytes_Click(object sender, EventArgs e)
        {
            if (client.IsConnected)
            {
                List<Rung.Net.Test.Utilities.DataProvider.TestSerializableClass> data = DataProvider.GetTestClassList();
                byte[] bytes = Rung.Common.SerializeHelper.Serialize(data);

                client.Send(bytes);
            }
        }

        // 【发送文件】
        private void btnSendFile_Click(object sender, EventArgs e)
        {
            if (client.IsConnected)
            {
                OpenFileDialog dialog = new OpenFileDialog();
                dialog.Multiselect = false;
                dialog.InitialDirectory = NetUtility.GetTempFolder();

                if (dialog.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
                {
                    if (client.IsBusy)
                        write("传输通道已占用...请稍后重试。");
                    else
                    {
                        write("传输中...");
                        client.Send(dialog.FileName);
                    }
                }
            }
        }

        // 【垃圾测试】
        private void btnTest_Click(object sender, EventArgs e)
        {
            int count = 25 * 1024 * 1024;
            using (System.IO.FileStream fs = new System.IO.FileStream(@"temp\000（25M）数据.txt", System.IO.FileMode.Create))
            {
                for (int i = 0; i < count; i++)
                {
                    fs.WriteByte(255);
                }
            } 
            
            count = 1024;
            using (System.IO.FileStream fs = new System.IO.FileStream(@"temp\000（1K）数据.txt", System.IO.FileMode.Create))
            {
                for (int i = 0; i < count; i++)
                {
                    fs.WriteByte(255);
                }
            }
        }

        void client_OnConnected(object sender, NetConnectedEventArgs e)
        {
            write("【连】");
        }

        void client_OnDisconnected(object sender, NetDisconnectedEventArgs e)
        {
            write("【断】");
        }

        void client_OnCacheProcessChanged(object sender, CacheProcessChangedEventArgs e)
        {
            if (!pb.IsDisposed && pb.IsHandleCreated)
            {
                pb.Invoke(new Action(delegate
                {
                    pb.Maximum = e.PackageCountTotal;

                    if (e.PackageCountReceived > e.PackageCountTotal)
                        pb.Value = e.PackageCountTotal;
                    else
                    pb.Value = e.PackageCountReceived;
                    
                    //txbMessage.Text += e.PackageCountReceived.ToString() + ",";
                }));
            }
        }

        void client_OnFileTransferComplited(object sender, FileTransferComplitedEventArgs e)
        {
            write("【传输完成】（OnFileTransferComplited 消息）");
            write(string.Format("文件：{0}", e.FileName));
            write(string.Format("长度：{0}", e.FileLength));
        }

        void client_OnReceived(object sender, NetReceivedEventArgs<byte[]> e)
        {
            write(string.Format("【OnReceived】：长度（{0}）", e.Data.Length));
            string receive = NetUtility.C(e.Data);
            int type = NetUtility.GetMessageType(receive);
            string body = NetUtility.GetMessageBody(receive);
            switch (type)
            {
                case MessageType.CacheFinished:
                    {
                        string[] bodys = body.Split(LevelSeperators.Level1);
                        string fileLength = bodys[0];
                        string oriFileName = bodys[1];
                        string desFileName = bodys[2];
                        write("【传输完成】（OnReceived 消息）");
                        write(string.Format("原文件名：{0}", oriFileName));
                        write(string.Format("本地文件：{0}", desFileName));
                        write(string.Format("长度：{0}", fileLength));
                    }
                    break;
            }
        }

        void write(string s)
        {
            if (!lbInfo.IsDisposed)
            {
                Invoke(new Action(delegate
                {
                    lbInfo.Items.Add(s);
                    lbInfo.SelectedIndex = lbInfo.Items.Count - 1;
                }));
            }
        }

        private string GetTestBody(int loop1, int loop2)
        {
            List<string> result = new List<string>();

            for (int i = 0; i < loop1; i++)
            {
                for (int j = 1; j <= loop2; j++)
                {
                    result.Add(new string('〇', j));
                }

                result.Add(new string('〇', loop2 + 1));

                for (int j = loop2; j >= 1; j--)
                {
                    result.Add(new string('〇', j));
                }
            }

            return string.Join("\r\n", result.ToArray());


            //for (int i = 0; i < loop1; i++)
            //{
            //    for (int k = 0; k < 5; k++)
            //    {
            //        for (int j = 0; j <= 9; j++)
            //        {
            //            result.Add(j.ToString());
            //        }
            //    }
            //}

            //for (int i = 0; i < 88; i++)
            //{
            //    result.Add("-");
            //}
            //for (int i = 0; i < 5; i++)
            //{
            //    result.Add("*");
            //}

            //return string.Join("", result.ToArray());
        }

    }
}
